package com.nowcoder.community.service;

import com.nowcoder.community.dao.elasticSearch.DiscussRepository;

import com.nowcoder.community.entity.DiscussPost;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class ElasticsearchService {

    @Autowired
    private DiscussRepository discussRepository;

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    public void saveDiscussPost(DiscussPost post) {
        discussRepository.save(post);
    }

    public void deleteDiscussPost(int id) {
        discussRepository.deleteById(id);
    }

public List<DiscussPost> searchDiscussPost(String keyword,int offset,int limit) throws IOException {
    SearchRequest request=new SearchRequest("dicusspost");
    //查询构造
    SearchSourceBuilder builder=new SearchSourceBuilder();
    MatchQueryBuilder queryBuilder=new MatchQueryBuilder("title",keyword);
    MatchQueryBuilder queryBuilder2=new MatchQueryBuilder("content",keyword);
    builder.query(queryBuilder);
    builder.query(queryBuilder2);
//高亮构造器
    HighlightBuilder highlightBuilder=new HighlightBuilder();
    highlightBuilder.field("title");
    highlightBuilder.field("content");
    //多个地方高亮
    highlightBuilder.requireFieldMatch(false);
    //高亮红色
    highlightBuilder.preTags("<span style='color:red'>");
    highlightBuilder.postTags("</span>");

    builder.highlighter(highlightBuilder);
    builder.from(offset);
    builder.size(limit);
    request.source(builder);
    SearchResponse response=restHighLevelClient.search(request, RequestOptions.DEFAULT);
    List<DiscussPost> list=new ArrayList<>();

    for (SearchHit hit : response.getHits().getHits()) {
        //解析高亮的字段，将原来的字段换为我们高亮的字段即可
        Map<String, HighlightField> highlightFieldMap= hit.getHighlightFields();
        HighlightField title1 = highlightFieldMap.get("title");
        HighlightField content1 = highlightFieldMap.get("content");

        //原来的字段
        Map<String,Object> map=hit.getSourceAsMap();
        DiscussPost discussPost=new DiscussPost();
        discussPost.setScore((Double) map.get("score"));
        discussPost.setType((Integer) map.get("type"));
        discussPost.setId((Integer) map.get("id"));

        discussPost.setCreateTime(new Date(Long.valueOf(map.get("createTime").toString())));
       discussPost.setCommentCount((Integer) map.get("commentCount"));
       discussPost.setStatus((Integer) map.get("status"));
       discussPost.setTitle((String) map.get("title"));
       discussPost.setContent((String) map.get("content"));
       discussPost.setUserId((Integer) map.get("userId"));


        if(title1!=null){
            Text[] fragments = title1.fragments();
            String n_title = "";
            for (Text text : fragments) {
                n_title += text;
            }

            discussPost.setTitle(n_title);
        }
        if(content1!=null){
            Text[] fragments = content1.fragments();
            String n_content = "";
            for (Text text : fragments) {
                n_content += text;
            }

            discussPost.setContent(n_content);
        }


        list.add(discussPost);
    }

    return list;
}

public long searchCount(String keyword) throws IOException {
        SearchRequest searchRequest=new SearchRequest("dicusspost");
        SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
        MatchQueryBuilder builder1=new MatchQueryBuilder("content",keyword);
        MatchQueryBuilder builder2=new MatchQueryBuilder("title",keyword);

        searchSourceBuilder.query(builder1);
        searchSourceBuilder.query(builder2);
    searchRequest.source(searchSourceBuilder);
    SearchResponse response=restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
    return response.getHits().getTotalHits().value;
}

}
